package mqtt

import (
	"manager/config"
	"manager/mqtt/publish"
	"manager/mqtt/subscribe"
	"time"

	MQTT "github.com/eclipse/paho.mqtt.golang"
	"hiscene.com/openplatform/common/logger"
)

////////////////////////////////////////////////////////////////////////////////

var (
	options *MQTT.ClientOptions
)

////////////////////////////////////////////////////////////////////////////////

// Start 启动
func Start() error {

	options = MQTT.NewClientOptions()
	{
		cfg := &config.MQTTCfg
		options.AddBroker(cfg.Server)
		options.SetCleanSession(cfg.CleanSession)
		options.SetAutoReconnect(cfg.Reconnect)

		if len(cfg.User) > 0 {
			options.SetUsername(cfg.User)
			options.SetPassword(cfg.Password)
		}
		if len(cfg.Store) > 0 {
			options.SetStore(MQTT.NewFileStore(cfg.Store))
		}
		if cfg.MaxReconInterval > 0 {
			options.SetMaxReconnectInterval(time.Duration(cfg.MaxReconInterval) * time.Second)
		}
	}

	if err := subscribe.Start(options); err != nil {
		logger.Log4g.Error("mqtt subscribe start error: %v", err)
		return err
	}

	if err := publish.Start(options); err != nil {
		logger.Log4g.Error("mqtt publish start error: %v", err)
		return err
	}

	return nil
}

// Stop 关闭
func Stop() {
	subscribe.Stop()
	publish.Stop()
}
